package com.spark.modules.test.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spark.common.constants.Constants;
import com.spark.common.constants.validGroup.AddGroup;
import com.spark.common.constants.validGroup.EditGroup;
import com.spark.common.core.Result;
import com.spark.common.query.QueryGenerator;
import com.spark.common.utils.TreeBuilderUtils;
import com.spark.common.utils.TreeIsLeafUtils;
import com.spark.modules.system.entity.SysDept;
import com.spark.modules.system.service.ISysDeptService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 * 系统部门表Controller
 *
 * @author LYCHEE
 * @date 2025/03/21 15:46
 */
@RestController
@RequestMapping(value = "/sys/dept")
public class SysDeptController {

    @Resource
    private ISysDeptService sysDeptService;

    /**
     * 懒加载列表查询
     * : 如果pid为空则查询所有父级,反之查询子级数据
     *
     * @param sysDept 系统部门表对象
     * @return 系统部门表列表
     */
    @PreAuthorize("@sp.hasPerm('sys:dept:query')")
    @GetMapping(value = "/queryLazyList")
    public Result<?> queryLazyList(SysDept sysDept) {
        QueryWrapper<SysDept> queryWrapper = QueryGenerator.initQueryWrapper(sysDept);
        if (StringUtils.isEmpty(sysDept.getPid())) {
            sysDept.setPid("0");
        }
        List<SysDept> list = sysDeptService.list(queryWrapper);
        return Result.ok(list);
    }

    /**
     * 列表查询
     *  :结果支持两种结构。1.平级('flat') 2.层级('layer')
     *  :需要再请求头中传入key为: model= 'flat' | 'layer'，默认 'layer'
     *
     * @param sysDept 系统部门表对象
     * @return 系统部门表列表: 结果支持两种结构。1.平级('flat') 2.层级('layer')
     */
    @PreAuthorize("@sp.hasPerm('sys:dept:query')")
    @GetMapping(value = "/queryList")
    public Result<?> queryList(SysDept sysDept, HttpServletRequest request) {
        String model = request.getHeader(Constants.TREE_MODEL_KEY);
        model = StringUtils.isEmpty(model) ? "layer" : model;
        QueryWrapper<SysDept> queryWrapper = QueryGenerator.initQueryWrapper(sysDept);
        List<SysDept> list = sysDeptService.list(queryWrapper);
        if ("layer".equals(model)){
            // 结构化为层级数据: 这里需要指定id,pid,children字段,此处为默认
            TreeBuilderUtils builder = new TreeBuilderUtils();
            // 结构化时设置叶子节点
            List<SysDept> buildTree = builder.buildTree(list, true);
            // 可以按照某个属性进行排序
            // builder.sortTreeNodes(buildTree,"{排序实体字段}",true);
            return Result.ok(buildTree);
        }
        return Result.ok(list);
    }

    /**
     * 通过ID查询
     *
     * @param id 主键
     * @return 系统部门表对象
     */
    @PreAuthorize("@sp.hasPerm('sys:dept:queryById')")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam String id) {
        SysDept sysDept = sysDeptService.getById(id);
        if (Objects.isNull(sysDept)) {
            return Result.fail("数据获取失败");
        }
        return Result.ok(sysDept);
    }

    /**
     * 新增
     *
     * @param sysDept 系统部门表对象
     * @return 成功或失败
     */
    @PreAuthorize("@sp.hasPerm('sys:dept:add')")
    @PostMapping(value = "/add")
    public Result<?> add(@Validated(AddGroup.class) @RequestBody SysDept sysDept) {
        // 设置数据叶子节点：需要指定父级ID(pid)和叶子节点(isLeaf)字段名称，此处为默认
        TreeIsLeafUtils<SysDept> isLeafUtils = new TreeIsLeafUtils<>(sysDeptService);
        isLeafUtils.dealIsLeaf(sysDept, "add", null);
        boolean save = sysDeptService.save(sysDept);
        return Result.flag(save);
    }

    /**
     * 编辑
     *
     * @param sysDept 系统部门表对象
     * @return 成功或失败
     */
    @PreAuthorize("@sp.hasPerm('sys:dept:edit')")
    @PostMapping(value = "/edit")
    public Result<?> edit(@Validated(EditGroup.class) @RequestBody SysDept sysDept) {
        // 设置数据叶子节点：需要指定父级ID(pid)和叶子节点(isLeaf)字段名称，此处为默认
        TreeIsLeafUtils<SysDept> isLeafUtils = new TreeIsLeafUtils<>(sysDeptService);
        isLeafUtils.dealIsLeaf(sysDept, "edit", null);
        boolean update = sysDeptService.updateById(sysDept);
        return Result.flag(update);
    }

    /**
     * 通过id删除
     *
     * @param id 主键
     * @return 成功或失败
     */
    @PreAuthorize("@sp.hasPerm('sys:dept:del')")
    @DeleteMapping(value = "/delete/{id}")
    public Result<?> delete(@PathVariable(name = "id") String id) {
        // 设置数据叶子节点：需要指定父级ID(pid)和叶子节点(isLeaf)字段名称，此处为默认
        TreeIsLeafUtils<SysDept> isLeafUtils = new TreeIsLeafUtils<>(sysDeptService);
        isLeafUtils.dealIsLeaf(null, "del", id);
        boolean update = sysDeptService.removeById(id);
        return Result.flag(update);
    }


}
